<template>
  <div class="app-container">
    <el-card>
      <!-- 筛选条件区域 -->
      <div class="filter-container">
        <el-form :model="listQuery" label-width="auto">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="6">
              <el-form-item label="文章标题">
                <el-input v-model.trim="listQuery.title" @input.native="filterPercentChar" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="6">
              <el-form-item label="分类">
                <el-select v-model="listQuery.tagId" filterable placeholder="请选择">
                  <el-option v-for="item in tags" :key="item.id" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="6">
              <el-form-item label-width="0">
                <el-button type="primary" @click="handleFilter">查询</el-button>
                <el-button @click="resetList">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 按钮区域 -->
      <div class="btn-container">
        <router-link :to="{ name: 'CreateArticle' }">
          <el-button type="primary" icon="el-icon-plus"> 添加 </el-button>
        </router-link>
      </div>

      <!-- 表格区域 -->
      <el-table :data="list" border highlight-current-row :stripe="true">
        <el-table-column label="#" width="60">
          <template slot-scope="{ $index }">
            <span>{{ $index + (listQuery.page - 1) * listQuery.limit + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="文章标题" prop="title" :show-overflow-tooltip="true" />
        <el-table-column label="分类" prop="tagName" width="120" :show-overflow-tooltip="true" />
        <el-table-column label="来源" prop="source" width="120" :show-overflow-tooltip="true" />
        <el-table-column label="作者" prop="author" width="120" :show-overflow-tooltip="true" />
        <el-table-column label="更新时间" prop="modTm" width="170" :show-overflow-tooltip="true" />
        <el-table-column label="状态" prop="status" width="96">
          <template slot-scope="{ row }">
            <el-tag :type="row.status | publishStatusColorFilter">{{ row.status | publishStatusNameFilter }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="{ row, $index }">
            <router-link
              :to="{
                name: 'EditArticle',
                params: { id: row.id, index: $index }
              }"
            >
              <el-button type="primary" size="mini"> 编辑 </el-button>
            </router-link>
            <el-button size="mini" type="danger" style="margin-left: 10px" @click="handleDelete(row, $index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </el-card>
  </div>
</template>

<script>
import { getList, deleteList } from '@/api/content/list' // 文章列表的查询、删除接口
import { getSelectTags } from '@/api/content/tags' // 文章分类的查询接口
import Pagination from '@/components/Pagination' // 分页组件
import { mapState } from 'vuex'

export default {
  name: 'ContentList',
  components: { Pagination },
  data() {
    return {
      list: [], // 列表数据
      total: 0, // 总数
      listQuery: {
        // 查询参数
        page: 1,
        limit: 10,
        tagId: undefined,
        title: undefined
      },
      rules: {
        // 表单验证规则
        title: [
          { required: true, message: '请输入标题名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度不能大于50位', trigger: 'blur' }
        ]
      },
      tags: [] // 文章分类
    }
  },
  computed: {
    ...mapState({
      editContent: (state) => state.pages.editContent // 从编辑页面传递过来的数据
    })
  },
  beforeRouteEnter(to, from, next) {
    // 进入之前缓存本组件，解决第一次不缓存列表页的问题
    next((vm) => {
      vm.$store.commit('permission/SET_INCLUDELIST', ['ContentList'])
      if (from.path.indexOf('/content/create') > -1 || from.path.indexOf('/content/edit') > -1) {
        vm.getList()
      }
    })
  },
  beforeRouteLeave(to, from, next) {
    // 跳转到详情页时缓存当前列表页，反之不缓存
    if (to.path.indexOf('/content/create') > -1 || to.path.indexOf('/content/edit') > -1) {
      this.$store.commit('permission/SET_INCLUDELIST', ['ContentList'])
    } else {
      this.$store.commit('permission/SET_INCLUDELIST', [])
      this.$destroy() // 销毁vue实例
    }
    next()
  },
  created() {
    // 组件创建完成
    this.getList()
    this.getTags()
  },
  methods: {
    async getTags() {
      // 获取文章分类
      try {
        const { data } = await getSelectTags('TAG_ID')
        this.tags = data
      } catch (error) {
        console.log(error)
      }
    },
    async getList() {
      // 获取列表数据
      try {
        const {
          data: { records, total }
        } = await getList(this.listQuery)
        this.list = records
        this.total = total
      } catch (error) {
        console.log(error)
      }
    },
    handleFilter() {
      // 查询
      this.listQuery.page = 1
      this.getList()
    },
    resetList() {
      // 重置
      this.listQuery = {
        page: 1,
        limit: 10,
        tagId: undefined,
        title: undefined
      }
      this.getList()
    },
    handleDelete(row, index) {
      // 点击删除按钮
      this.$confirm('此操作将删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { message } = await deleteList(row.id)
          this.$message({
            type: 'success',
            message: message
          })
          this.getList()
        })
        .catch(() => {})
    }
  }
}
</script>
